package com.rico.kok.controller.post;

import com.github.pagehelper.PageInfo;
import com.rico.kok.entity.*;
import com.rico.kok.entity.povos.CommentAndComment;
import com.rico.kok.entity.povos.PostUser;
import com.rico.kok.entity.povos.UserComment;
import com.rico.kok.entity.povos.UserPosts;
import com.rico.kok.service.interf.*;
import com.rico.kok.tool.MessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.github.pagehelper.PageHelper;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class PostController {

    //内容
    @Autowired
    PostService postService;

    //异常消息
    @Autowired
    MessageUtils messageUtils;

    //点赞
    @Autowired
    LikeService likeService;

    //关注
    @Autowired
    FollowService followService;

    //收藏
    @Autowired
    CollectionService collectionService;

    //标签
    @Autowired
    LabelService labelService;

    //内容和标签关联
    @Autowired
    PostLabelService postLabelService;

    //评论
    @Autowired
    CommentService commentService;

    //用户信息
    @Autowired
    UserService userService;

    //评论点赞
    @Autowired
    CommentLikeService commentLikeService;

    //获取内容列表
    @RequestMapping("/browseList.htm")
    public String getList(@RequestParam(value = "num", defaultValue = "1") Integer pageNum, @RequestParam(value = "label", defaultValue = "0") Integer labelId, Model model, HttpSession session) {
        List<Label> labels = labelService.selectAllLabel();
        session.setAttribute("labels", labels);
        if (labelId > 0) {
            PostLabel postLabel = new PostLabel();
            postLabel.setLabelId(labelId);
            List<PostLabel> list = postLabelService.selectLabel(postLabel);
            List<Integer> postIds = new ArrayList<>();
            for (PostLabel pl : list) {
                postIds.add(pl.getPostId());
            }
            List<PostUser> postUsers;
            if (list.size() == 0) {
                postUsers = new ArrayList<>();
            } else {
                PageHelper.startPage(pageNum, 6, "post_id desc");
                postUsers = postService.selectPostByPostIds(postIds);
            }
            PageInfo<PostUser> pageInfo = new PageInfo<>(postUsers);
            String url = "/browseList.htm?label=" + labelId + "&num=";
            model.addAttribute("pageInfo", pageInfo);
            model.addAttribute("url", url);
            return "post_list";
        }
        PageHelper.startPage(pageNum, 6, "post_id desc");
        ArrayList<PostUser> userPosts = postService.selectPosts(new Post());
        PageInfo<PostUser> pageInfo = new PageInfo<>(userPosts);
        String url = "/browseList.htm?num=";
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("url", url);
        return "post_list";

    }

    //浏览内容
    @RequestMapping("/browsePost.htm")
    public String getPost(@RequestParam("id") String postId, Model model, HttpSession session) {
        //获取登录信息
        User loginUser = (User) session.getAttribute("user");
        Post post = new Post();
        try {
            int i = Integer.parseInt(postId);
            post.setPostId(i);
        } catch (Exception e) {
            System.out.println("不合法内容ID");
            messageUtils.setMsg(model, "错误", "不合法内容ID", "error");
            return "msg";
        }
        ArrayList<PostUser> postUsers = postService.selectPosts(post);
        if (postUsers != null && postUsers.size() > 0) {
            PostUser postUser = postUsers.get(0);
            model.addAttribute("postUser", postUser);
            Map<Integer, CommentLike> commentLikeMap = new HashMap<>();

            //获取点赞信息
            if (loginUser != null) {
                CommentLike commentLike = new CommentLike();
                commentLike.setCommentPostId(postUser.getPost().getPostId());
                commentLike.setCommentUserId(loginUser.getUserId());
                List<CommentLike> commentLikes = commentLikeService.selectCommentLikes(commentLike);
                for (CommentLike commentLike1 : commentLikes) {
                    commentLikeMap.put(commentLike1.getCommentCommentId(), commentLike1);
                }
            }

            //加载评论
            Comment comment = new Comment();
            comment.setPostId(postUser.getPost().getPostId());
            comment.setIsDelete((byte) 0);
            //获取一层评论
            List<Comment> comments = commentService.selectComment(comment);
            //所有评论
            List<CommentAndComment> commentAndComments = new ArrayList<>();
            //获取评论作者
            List<Integer> userIds = new ArrayList<>();
            for (Comment c : comments) {
                userIds.add(c.getUserId());
            }
            Map<Integer, User> userMap = new HashMap<>();
            if (userIds.size()>0) {
                List<User> users = userService.selectUsersByIds(userIds);
                for (User user : users) {
                    userMap.put(user.getUserId(), user);
                }
            }
            //组装一层评论和二层评论
            for (Comment c : comments) {
                //定义一个一层评论和二层评论的POVO
                CommentAndComment commentAndComment = new CommentAndComment();

                //一层评论
                //为一层评论添加点赞信息
                if (loginUser != null) {
                    CommentLike commentLike = commentLikeMap.get(c.getCommentId());
                    if (commentLike == null) {
                        c.setCommentIsLike(false);
                    } else {
                        c.setCommentIsLike(true);
                    }
                }
                //定义一个用户和评论POVO
                UserComment firstUserComment = new UserComment();
                firstUserComment.setComment(c);
                //获取对应用户信息
                firstUserComment.setUser(userMap.get(c.getUserId()));
                //封装一条一层和二层评论
                //设置一层评论
                commentAndComment.setFirstUserComment(firstUserComment);

                //二层评论
                List<UserComment> secondUserComments = new ArrayList<>();
                //获取二层评论
                Comment secondComment = new Comment();
                secondComment.setToCommentId(c.getCommentId());
                List<Comment> secondComments = commentService.selectComment(secondComment);
                List<Integer> secondUserIds = new ArrayList<>();
                for (Comment secondC : secondComments) {
                    secondUserIds.add(secondC.getUserId());
                }
                Map<Integer, User> secondUserMap = new HashMap<>();
                //二层评论者信息
                if (secondUserIds.size()>0){
                    List<User> secondUsers = userService.selectUsersByIds(secondUserIds);
                    for (User secondUser : secondUsers) {
                        secondUserMap.put(secondUser.getUserId(), secondUser);
                    }
                }
                //封装二层评论
                for (Comment secondC : secondComments) {
                    //为二层评论添加点赞信息
                    if (loginUser!=null){
                        CommentLike commentLike = commentLikeMap.get(secondC.getCommentId());
                        if (commentLike==null){
                            secondC.setCommentIsLike(false);
                        }else {
                            secondC.setCommentIsLike(true);
                        }
                    }
                    UserComment secondUserComment = new UserComment();
                    secondUserComment.setUser(secondUserMap.get(secondC.getUserId()));
                    secondUserComment.setComment(secondC);
                    secondUserComments.add(secondUserComment);
                }
                commentAndComment.setSecondUserComments(secondUserComments);
                commentAndComments.add(commentAndComment);
            }
            model.addAttribute("commentAndComments", commentAndComments);
            //判定是否关注了用户
            follow(model, session, postUsers.get(0).getUser().getUserId());
            //判定是否登录
            if (loginUser != null) {
                //如果登录则判定是否点赞此篇内容
                post.setUserId(loginUser.getUserId());
                Integer isLike = likeService.isLike(post);
                if (isLike == null) {
                    model.addAttribute("isLike", false);
                } else {
                    model.addAttribute("isLike", true);
                }
                //如果登录则判定是否收藏此篇内容
                Integer isCollection = collectionService.isCollection(post);
                if (isCollection == null) {
                    model.addAttribute("isCollection", false);
                } else {
                    model.addAttribute("isCollection", true);
                }
            } else {
                //未登录是默认未点赞未收藏状态
                model.addAttribute("isLike", false);
                model.addAttribute("isCollection", false);
            }
            return "post/browse_post";
        }
        messageUtils.setMsg(model, "错误", "内容消失了", "error");
        return "msg";
    }

    //判定用户是否是自己并判断是否关注用户
    private void follow(Model model, HttpSession session, Integer visitId) {
        //默认用户访问的不是自己
        model.addAttribute("itsMe", false);
        //判定是否登录
        if (session.getAttribute("user") != null) {
            model.addAttribute("userId", visitId);
            //登录后判断是否关注用户
            User user = (User) session.getAttribute("user");
            int isFollow = followService.selectAllFollowsId(user.getUserId()).indexOf(visitId);
            //判定是否是用户自己
            if (visitId.equals(user.getUserId())) {
                model.addAttribute("itsMe", true);
            }
            if (isFollow == -1) {
                model.addAttribute("isFollow", false);
            } else {
                model.addAttribute("isFollow", true);
            }
        } else {
            //未登录设置未登录
            model.addAttribute("isFollow", false);
        }
    }

}
